package cn.com.utt.common.message;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.annotation.JSONField;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.serializer.SerializerFeature;

public class Message {
	@JSONField(name="id") 
	private String id;
	@JSONField(name="type") 
	private String type;

	public final static SerializerFeature[] features = { SerializerFeature.WriteNullListAsEmpty,
			SerializerFeature.WriteNullNumberAsZero, SerializerFeature.WriteNullStringAsEmpty,
			SerializerFeature.DisableCircularReferenceDetect };

	public Message() {
		super();
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

	public String encode(){
		return JSON.toJSONString(this);
	}

	public void decode(byte[] buf){
		Message message = JSON.parseObject(buf, Message.class, Feature.IgnoreNotMatch);
		this.id = message.getId();
		this.type = message.getType();
	}

	public static Message NewMessage(byte[] bytes) {
		System.out.println("json:"+new String(bytes));
		Message message = JSON.parseObject(bytes, Message.class, Feature.IgnoreNotMatch);
		System.out.println(message);
		System.out.println(message.getType());
		switch (MessageType.valueOf(message.getType().toUpperCase())) {
		case GET:
			return new Get();
		case GETRESP:
			return new GetResp();
		case GETXML:
			return new GetXml();
		case GETXMLRESP:
			return new GetXmlResp();
		case SET:
			return new Set();
		case SETRESP:
			return new SetResp();
		case DOWNLOAD:
			return new Download();
		case DOWNLOADRESP:
			return new DownloadResp();
		case REBOOT:
			return new Reboot();
		case REBOOTRESP:
			return new RebootResp();
		case RESET:
			return new Reset();
		case RESETRESP:
			return new ResetResp();
		case UPLOAD:
			return new Upload();
		case UPLOADRESP:
			return new UploadResp();
		case COMMAND:
			return new Command();
		case COMMANDRESP:
			return new CommandResp();
		case DISCONNECT:
			return new Disconnect();
		default:
			return null;
		}
	}
}
